package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Dialog;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.SelCategoryAdapter;
import flc.ast.adapter.VideoAdapter;
import flc.ast.bean.MyAlbumBean;
import flc.ast.databinding.ActivityLocalVideoBinding;
import flc.ast.dialog.DeleteDialog;
import flc.ast.dialog.EditDialog;
import flc.ast.dialog.InfoDialog;
import flc.ast.dialog.RenameDialog;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.view.container.StkRecycleView;

public class LocalVideoActivity extends BaseAc<ActivityLocalVideoBinding> {

    private VideoAdapter videoAdapter;
    private List<SelectMediaEntity> listShow = new ArrayList<>();
    private SelCategoryAdapter categoryAdapter;
    private Dialog mySelCategoryDialog;
    private Dialog myAddCategoryDialog;
    private EditText dialogAdd;
    private int oldPosition;

    @Override
    protected int onCreate() {
        return R.layout.activity_local_video;
    }

    @Override
    protected void initView() {
        mDataBinding.ivLocalVideoBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.rvVideoList.setLayoutManager(new GridLayoutManager(mContext, 2));
        videoAdapter = new VideoAdapter();
        mDataBinding.rvVideoList.setAdapter(videoAdapter);
        videoAdapter.addChildClickViewIds(R.id.ivVideoItemEdit);
        videoAdapter.setOnItemClickListener(this);
        videoAdapter.setOnItemChildClickListener(this);

        categoryAdapter = new SelCategoryAdapter();
        categoryAdapter.setOnItemClickListener(this);

        //选择视频分类弹框
        selCategoryDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.flPrivacyFile://隐私文件
                String filePath = FileUtil.generateFilePath(Content.myPrivacy, "." + FileUtils.getFileExtension(listShow.get(oldPosition).getPath()));
                FileUtils.copy(listShow.get(oldPosition).getPath(), filePath);
                mySelCategoryDialog.dismiss();
                ToastUtils.showShort(getString(R.string.add_suc));
                break;
            //新建视频分类弹框
            case R.id.tvDialogAddCategoryConfirm://确定
                addCategory();
                break;
            case R.id.tvDialogAddCategoryCancel://取消
                myAddCategoryDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == videoAdapter) {
            PlayActivity.videoPath = videoAdapter.getItem(position).getPath();
            startActivity(PlayActivity.class);
        } else if (adapter == categoryAdapter) {
            if (position == categoryAdapter.getItemCount() - 1) {
                mySelCategoryDialog.dismiss();
                //新建相册弹框
                addCategoryDialog();
                myAddCategoryDialog.show();
                return;
            }
            String filePath = FileUtil.generateFilePath(Content.myVideo + "/" + categoryAdapter.getItem(position).getName(), "." + FileUtils.getFileExtension(listShow.get(position).getPath()));
            FileUtils.copy(listShow.get(position).getPath(), filePath);
            mySelCategoryDialog.dismiss();
            ToastUtils.showShort(getString(R.string.add_suc));
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivVideoItemEdit://编辑
                oldPosition = position;
                showEditDialog(position);
                break;
        }
    }

    @Override
    protected void initData() {
        getData();
        getCategoryData();
    }

    //获取视频和图片数据
    private void getData() {
        listShow.clear();
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.VIDEO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    listShow.addAll(selectMediaEntities);
                    videoAdapter.setList(selectMediaEntities);
                    mDataBinding.rvVideoList.setVisibility(View.VISIBLE);
                    mDataBinding.tvVideoNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvVideoList.setVisibility(View.GONE);
                    mDataBinding.tvVideoNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void showEditDialog(int position) {
        EditDialog dialog = new EditDialog(mContext);
        dialog.setListener(new EditDialog.Ilistener() {
            @Override
            public void clickRename() {
                showRenameDialog(position);
            }

            @Override
            public void clickShare() {
                IntentUtil.shareVideo(mContext, listShow.get(position).getPath());
            }

            @Override
            public void clickAddFolder() {
                getCategoryData();
                mySelCategoryDialog.show();
            }

            @Override
            public void clickInfo() {
                showInfoDialog(position);
            }

            @Override
            public void clickDelete() {
                showDeleteDialog(position);
            }
        });
        dialog.show();
    }

    private void showRenameDialog(int position) {
        RenameDialog dialog = new RenameDialog(mContext);
        dialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                FileUtils.rename(listShow.get(position).getPath(), name + "." + FileUtils.getFileExtension(listShow.get(position).getPath()));
                getData();
            }
        });
        dialog.show();
    }

    private void showInfoDialog(int position) {
        InfoDialog dialog = new InfoDialog(mContext);
        dialog.videoPath = listShow.get(position).getPath();
        dialog.show();
    }

    private void showDeleteDialog(int position) {
        DeleteDialog dialog = new DeleteDialog(mContext);
        dialog.setListener(new DeleteDialog.Ilistener() {
            @Override
            public void clickDelete() {
                delete(position);
            }
        });
        dialog.show();
    }

    private void delete(int position) {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //从此文件夹删除
                        mContext.getContentResolver().delete(Uri.parse(listShow.get(position).getUri()), null, null);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        getData();
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }

    private void getCategoryData() {
        List<MyAlbumBean> listCategory = new ArrayList<>();
        String path = PathUtils.getFilesPathExternalFirst() + Content.myVideo;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                List<File> data = FileUtils.listFilesInDir(path + "/" + file.getName());
                List<String> list = new ArrayList<>();
                for (File datum : data) {
                    list.add(datum.getPath());
                }
                listCategory.add(new MyAlbumBean(file.getName(), list));
            }
        }
        if (listCategory != null && listCategory.size() > 0) {
            listCategory.add(new MyAlbumBean());
            categoryAdapter.setList(listCategory);
        }
    }

    private void addCategory() {
        String categoryName = dialogAdd.getText().toString();
        if (TextUtils.isEmpty(categoryName)) {
            ToastUtils.showShort(R.string.please_input_category_name);
            return;
        }
        myAddCategoryDialog.dismiss();
        //准备数据
        String path = PathUtils.getFilesPathExternalFirst() + Content.myVideo + "/" + categoryName;
        if (FileUtils.isFileExists(path)) {
            ToastUtils.showShort(getString(R.string.category_is_exist));
        } else {
            FileUtils.createOrExistsDir(path);
            ToastUtils.showShort(getString(R.string.add_category_suc));
        }
    }

    //选择视频分类弹框
    private void selCategoryDialog() {
        mySelCategoryDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_save, null);
        mySelCategoryDialog.setContentView(inflate);
        mySelCategoryDialog.setCancelable(true);
        Window dialogWindow = mySelCategoryDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        FrameLayout frameLayout = inflate.findViewById(R.id.flPrivacyFile);
        RecyclerView recycleView = inflate.findViewById(R.id.rvCategoryList);
        recycleView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        recycleView.setAdapter(categoryAdapter);
        frameLayout.setOnClickListener(this);
    }

    //新建视频分类弹框
    private void addCategoryDialog() {
        myAddCategoryDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_category, null);
        myAddCategoryDialog.setContentView(inflate);
        myAddCategoryDialog.setCancelable(true);
        Window dialogWindow = myAddCategoryDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogAddCategoryConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogAddCategoryCancel);
        dialogAdd = inflate.findViewById(R.id.etDialogAddCategoryText);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

}